<template>
	<view v-if="show" class="phone-auth-modal">
		<view class="mask" @tap="onCancel"></view>
		<view class="content">
			<view class="header">
				<view class="shop-info">
					<image class="logo" :src="hotelInfo.logo" mode="aspectFit"></image>
					<view class="info">
						<view class="title">登录{{ hotelInfo.name }}</view>
						<view class="desc">授权后可体验更多功能</view>
					</view>
				</view>
			</view>

			<view class="body">
				<!-- 头像编辑 -->
				<view class="avatar-section" v-if="!hasNickname">
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<image class="avatar" :src="tempUserInfo.avatarUrl || '/static/avatar/default.png'"
							mode="aspectFill"></image>
						<text class="tip">点击设置头像</text>
					</button>
				</view>

				<!-- 昵称编辑 -->
				<view class="nickname-section" v-if="!hasNickname">
					<input type="nickname" class="nickname-input" placeholder="请输入昵称" :value="tempUserInfo.nickName"
						@input="onNicknameChange" />
				</view>
			</view>

			<view class="footer">
				<button class="auth-btn primary" :class="{ disabled: isAuthBtnDisabled }" :disabled="isAuthBtnDisabled"
					open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">
					授权手机号并登录
				</button>
				<button class="auth-btn secondary" @tap="onCancel">
					暂不登录
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		userApi
	} from '@/api'
	import {
		userStorage
	} from '@/utils/storage'

	export default {
		name: 'PhoneAuth',
		props: {
			show: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				tempUserInfo: {
					avatarUrl: '',
					nickName: ''
				},
				avatarServerUrl:'',
				hotelInfo: {
					name: '临海荣舍民宿',
					logo: '/static/logo.jpg'
				}
			}
		},
		computed: {
			hasNickname() {
				const userInfo = userStorage.getUserInfo()
				return userInfo && userInfo.username
			},
			isAuthBtnDisabled() {
				if (!this.hasNickname) {
					return !this.tempUserInfo.avatarUrl || !this.tempUserInfo.nickName
				}
				return false
			}
		},
		created() {
			// 从缓存获取店铺信息
			const hotelInfo = uni.getStorageSync('hotelInfo')
			if (hotelInfo) {
				this.hotelInfo = hotelInfo
			}
			const userInfo = userStorage.getUserInfo()
			if (userInfo) {
				this.tempUserInfo.avatarUrl = userInfo.avatar
				this.tempUserInfo.nickName = userInfo.username
			}
		},
		methods: {
			onChooseAvatar(e) {
				const that = this
				const token = userStorage.getToken()
				
				// 先设置临时预览
				that.tempUserInfo.avatarUrl = e.detail.avatarUrl
				
				wx.uploadFile({
					url: that.$baseUrl + "/common/upload",
					filePath: e.detail.avatarUrl,
					name: 'file',
					header: {
						"Authorization": token ? `Bearer ${token}` : '',
					},
					success(res) {
						// 解析返回的数据
						const data = JSON.parse(res.data)
						if (data.code === 200) {
							// 更新为服务器返回的地址，只保存相对路径
							that.tempUserInfo.avatarUrl = data.fileName
						} else {
							uni.showToast({
								title: data.msg || '上传失败',
								icon: 'none'
							})
						}
					},
					fail(err) {
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
						console.error('上传失败:', err)
					}
				})
			},
			onNicknameChange(e) {
				this.tempUserInfo.nickName = e.detail.value
			},
			handleGetPhoneNumber(e) {
				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					uni.showLoading({
						title: '登录中...'
					})

					uni.login({
						provider: 'weixin',
						success: (loginRes) => {
							const loginData = {
								code: loginRes.code,
								encryptedData: e.detail.encryptedData,
								iv: e.detail.iv
							}

							userApi.wxPhoneLogin(loginData).then(res => {
								userStorage.setToken(res.data.token)
								userStorage.setUserInfo(res.data.userInfo)
								userStorage.setNeedPhone(false)

								uni.hideLoading()
								uni.showToast({
									title: '登录成功',
									icon: 'success'
								})

								this.$emit('success', res.data)
								
								// 登录成功后，如果有未完成的头像上传，继续上传
								if (this.tempUserInfo.avatarUrl && this.tempUserInfo.avatarUrl.startsWith('wxfile://')) {
									this.onChooseAvatar({ detail: { avatarUrl: this.tempUserInfo.avatarUrl } })
								}
							}).catch(err => {
								uni.hideLoading()
								uni.showToast({
									title: err.message || '登录失败',
									icon: 'none'
								})
								this.$emit('fail', err)
							})
						}
					})
				} else {
					this.$emit('cancel')
				}
			},
			onCancel() {
				this.$emit('cancel')
			}
		}
	}
</script>

<style lang="scss">
	.phone-auth-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 99999;

		.mask {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0, 0, 0, 0.6);
			backdrop-filter: blur(4px);
		}

		.content {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			background: #fff;
			border-radius: 24rpx 24rpx 0 0;
			overflow: hidden;
			max-height: 90vh;
			display: flex;
			flex-direction: column;

			.header {
				padding: 40rpx;
				flex-shrink: 0;
				/* 防止头部被压缩 */

				.shop-info {
					display: flex;
					align-items: center;
					margin-bottom: 40rpx;

					.logo {
						width: 120rpx;
						height: 120rpx;
						border-radius: 16rpx;
						margin-right: 24rpx;
						flex-shrink: 0;
					}

					.info {
						flex: 1;
						text-align: left;

						.title {
							font-size: 36rpx;
							font-weight: 600;
							color: #333;
							margin-bottom: 12rpx;
						}

						.desc {
							font-size: 28rpx;
							color: #666;
						}
					}
				}
			}

			.body {
				padding: 0 40rpx;
				flex: 1;
				/* 允许内容区域伸缩 */
				// overflow-y: auto; /* 内容过多时可滚动 */

				.avatar-section {
					display: flex;
					justify-content: center;
					margin-bottom: 32rpx;

					.avatar-wrapper {
						padding: 0;
						background: none;
						display: flex;
						flex-direction: column;
						align-items: center;

						&::after {
							border: none;
						}

						.avatar {
							width: 160rpx;
							height: 160rpx;
							border-radius: 80rpx;
							margin-bottom: 16rpx;
						}

						.tip {
							font-size: 26rpx;
							color: #999;
						}
					}
				}

				.nickname-section {
					margin-bottom: 40rpx;

					.nickname-input {
						width: 100%;
						height: 88rpx;
						background: #f8f8f8;
						border-radius: 44rpx;
						padding: 0 32rpx;
						font-size: 28rpx;
						color: #333;
					}
				}
			}

			.footer {
				padding: 40rpx;
				flex-shrink: 0;
				/* 防止底部被压缩 */

				.auth-btn {
					width: 100%;
					height: 88rpx;
					line-height: 88rpx;
					border-radius: 44rpx;
					font-size: 32rpx;
					margin-bottom: 24rpx;

					&.primary {
						background: linear-gradient(to right, #1989fa, #39a0ff);
						color: #fff;
						font-weight: 500;

						&:active {
							opacity: 0.9;
						}

						&.disabled {
							background: #f5f5f5;
							border: 2rpx solid #e8e8e8;
							color: #ccc;
							opacity: 1;
							box-shadow: none;

							&:active {
								opacity: 1;
							}
						}
					}

					&.secondary {
						background: #f8f8f8;
						color: #666;

						&:active {
							opacity: 0.8;
						}
					}

					&:last-child {
						margin-bottom: 0;
					}
				}
			}
		}
	}
</style>